package com.timemaneger.thinkintime;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.timemaneger.thinkintime.richeditor.RichEditor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class NoteBookActivity extends AppCompatActivity {
    private InputMethodManager imm;
    private WebView book_editor;
    private File[]subFile;
    private int index=0;
    private ImageView delete_note;
    private String path="/storage/emulated/0/Html/平行时光-2131230822";
    private Button pre_note;
    private Button next_note;
    private String CSS_STYPE = "<head>\n" +
            "    <meta name=\"viewport\" content=\"user-scalable=no\">\n" +
            "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
            "    <link rel=\"stylesheet\" type=\"text/css\" href=\"normalize.css\">\n" +
            "    <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n" +
            "</head>";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//
        setContentView(R.layout.activity_note_book);
        init();
    }

    private void init() {
        book_editor=(WebView) findViewById(R.id.book_editor);

        Intent result=getIntent();
        path=result.getStringExtra("path");


        //TODO保存html文件
        File dir=new File(path);
        subFile=dir.listFiles();

        pre_note=(Button) findViewById(R.id.pre_note);
        pre_note.setEnabled(false);
        pre_note.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index--;
                showEditor();
            }
        });
        next_note=(Button) findViewById(R.id.next_note);
        next_note.setEnabled(false);
        next_note.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index++;
                showEditor();
            }
        });
        delete_note=(ImageView) findViewById(R.id.delete_note);
        delete_note.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file=new File(path,subFile[index].getName());
                file.delete();
                subFile=new File(path).listFiles();
                if(index>=subFile.length)
                    index--;
                if(index<0){
                    delete_note.setEnabled(false);
                    delete_note.setImageResource(R.mipmap.delete_book_not);
                    book_editor.setBackgroundResource(R.mipmap.block);
//            book_editor.setHtml("<h1>无</h1>");
                    book_editor.loadDataWithBaseURL(null,"<h1>无</h1>","text/html","utf-8",null);
//            book_editor.loadData("<h1>无</h1>","text/html",null);

                    return;
                }
                showEditor();
            }
        });
        if(subFile.length==0){
            delete_note.setEnabled(false);
            delete_note.setImageResource(R.mipmap.delete_book_not);
            book_editor.setBackgroundResource(R.mipmap.block);
//            book_editor.setHtml("<h1>无</h1>");
            book_editor.loadDataWithBaseURL(null,"<h1>无</h1>","text/html","utf-8",null);
//            book_editor.loadData("<h1>无</h1>","text/html",null);
            return;
        }
        showEditor();


        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(book_editor.getWindowToken(),0);
        imm.showSoftInput(book_editor,InputMethodManager.SHOW_FORCED);
        book_editor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                try {
                    imm.hideSoftInputFromWindow(book_editor.getWindowToken(), 0); //强制隐藏键盘
                    imm.showSoftInput(book_editor,InputMethodManager.SHOW_FORCED);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    private void showEditor() {
        if(index>0){
            pre_note.setEnabled(true);
        }else if(index==0){
            pre_note.setEnabled(false);
        }
        if(index<subFile.length-1){
            next_note.setEnabled(true);
        } else if(index==subFile.length-1){
            next_note.setEnabled(false);
        }
        String fileName=subFile[index].getName();
        String background;
        String title;
        try{
            background=fileName.split("-")[1];
            background=background.substring(0,background.indexOf(".html"));
            title=fileName.split("-")[0];
        }catch (Exception e){
            background=null;
            title=fileName.substring(0,fileName.indexOf(".html"));
        }
        String html="";
        try{
            File file=new File(path,fileName);
            FileInputStream fis=new FileInputStream(file);
            byte[]b=new byte[1024];
            int len=0;
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            while ((len=fis.read(b))!=-1){
                baos.write(b,0,len);
            }
            byte[]data=baos.toByteArray();
            baos.close();
            html=new String(data);
            html="<h1>"+title+"</h1>"+html;
            book_editor.setBackgroundColor(0);
            if(background==null){

            }else {
                int i=0;
                if(background.equals("desert")){
                    i=R.mipmap.desert;
                }else if(background.equals("bamboo")){
                    i=R.mipmap.bamboo;
                }else if(background.equals("lemon")){
                    i=R.mipmap.lemon;
                }else if(background.equals("leaf")){
                    i=R.mipmap.leaf;
                }else if(background.equals("block")){
                    i=R.mipmap.block;
                }

                book_editor.setBackgroundResource(i);

            }

            book_editor.loadDataWithBaseURL("file:///android_asset/",CSS_STYPE+html,"text/html","utf-8",null);
//            book_editor.loadData(html,"text/html",null);
//            book_editor.setHtml(html);
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }
}
